﻿using System;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using ZSZ.Application.IService;
using ZSZ.Core.Entities;
using ZSZ.DTO;
using ZSZ.EntityFramework;
using ZSZ.Service;

namespace ZSZ.Application.Service
{
    public class CityService : Repository<CityEntity>, ICityService
    {

        public long AddNew(string cityName)
        {
            //判断是否存在任何一条数据满足 c.Name == cityName
            //即存在这样一个名字的城市
            //如果只是判断“是否存在”，那么用Any效率比Where().count()效率高
            //Where(c => c.Name == cityName).Count()>0
            var exists = GetAllDataEntity().Any(c => c.Name == cityName);
            if (exists)
            {
                throw new ArgumentException("城市已经存在");
            }
            CityEntity city = new CityEntity();
            city.Name = cityName;
            SaveOrUpdate(city,true);
            return city.Id;
        }

        private CityDTO ToDTO(CityEntity city)
        {
            var dto = new CityDTO
            {
                CreateDateTime = city.CreateDateTime,
                Id = city.Id,
                Name = city.Name
            };
            return dto;
        }

        public CityDTO[] GetAll()
        {
            return GetAllDataEntity().AsNoTracking()
                .ToList().Select(c => ToDTO(c)).ToArray();
        }

        public CityDTO GetById(long id)
        {
            var city = GetOneById(id);
            if (city == null)
            {
                return null;
            }
            return ToDTO(city);
           
        }

        public CityService(ZSZDbContext context) : base(context)
        {
        }
    }
}
